from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
import pandas as pd
from localdatahost.local_datahost import DataHost


class DataViewWidget(QWidget):
    def __init__(self, parent=None):
        super(DataViewWidget, self).__init__(parent)

        hhbox = QHBoxLayout()  # 横向布局

        self.dataHost = DataHost()

        self.tableWidget = QTableWidget()

        self.tableWidget.setColumnCount(5)
        self.tableWidget.setRowCount(4)  # 设置表格有两行五列
        self.tableWidget.setHorizontalHeaderLabels(["name", "rows", 'cols'])

        self.refresh_table()
        self.button = QPushButton('添加数据')
        hhbox.addWidget(self.button)
        self.button.clicked.connect(self.load_file)

        self.button2 = QPushButton('删除首行数据')
        hhbox.addWidget(self.button2)
        self.button2.clicked.connect(self.delete_first_data)

        hhbox.addWidget(self.tableWidget)  # 把表格加入布局

        self.setLayout(hhbox)  # 创建布局

        self.setWindowTitle("我是一个表格")
        self.setWindowIcon(QIcon("icon.png"))
        self.resize(920, 240)
        self.show()

    def delete_first_data(self):
        text = self.tableWidget.item(0, 0).text()
        self.dataHost.delete_data(text)
        self.refresh_table()
        pass

    def load_file(self):
        file_name = 'file_%d' % len(self.dataHost.vars.keys())
        self.dataHost.set_data(file_name, pd.read_csv('../demos/class.csv'))
        self.refresh_table()

    def refresh_table(self):
        self.tableWidget.clear()
        all_data_names = self.dataHost.all_data_names

        for i, n in enumerate(all_data_names):
            self.tableWidget.setItem(i, 0, QTableWidgetItem(n))
            info_dic = self.dataHost.get_info(n)
            print(n, info_dic)
            self.tableWidget.setItem(i, 1, QTableWidgetItem(info_dic['row']))
            self.tableWidget.setItem(i, 2, QTableWidgetItem(info_dic['col']))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    dlg = DataViewWidget()
    sys.exit(app.exec_())
